/*
 * @Author: myw
 * @Email: 516378746@qq.com
 * @Date: 2020-03-13 11:21:10
 * @Descripttion: 
 */
import { Directive, ElementRef, HostListener, AfterViewInit, Renderer2 } from '@angular/core';

@Directive({
    selector: '[appDragModal]'
})
export class DragModalDirective {
    private isDown = false;
    private distTop: number = 0;
    private distLeft: number = 0;
    private modalTop: number = 0;
    private modalLeft: number = 0;
    constructor(
        private el: ElementRef,
        private render: Renderer2
    ) { }

    ngAfterViewInit(): void {
        this.mousedown();
        this.mousemove();
        this.mouseup();

        this.docLeave();
        this.docClick();
    }

    docLeave(){
        this.render.listen(document.body, 'mouseleave', ()=>{
            this.isDown = false;
        })
    }
    docClick(){
        this.render.listen(document.body, 'click', ()=>{
            this.isDown = false;
        })
    }
    mousedown() {
        this.render.listen(this.modalEle, 'mousedown', (ev) => {
            if (ev.target.tagName !== 'INPUT' && ev.target.tagName !== 'TEXTAREA') {
                this.isDown = true;

                this.modalTop = this.modalEle.offsetTop;
                this.modalLeft = this.modalEle.offsetLeft;

                this.distTop = ev.clientY - this.modalTop - 100;                // 100 => 顶部和页签高度总和
                this.distLeft = ev.clientX - this.modalLeft - 200;              // 200 => 左侧菜单宽度
                this.setStyle(this.modalTop, this.modalLeft);
                ev.preventDefault();
            }
        })
    }
    mousemove() {
        this.render.listen(this.modalEle, "mousemove", (ev) => {
            if (this.isDown) {
                let _left = ev.clientX - this.distLeft - 200;
                let _top = ev.clientY - this.distTop - 100;
                this.setStyle(_top, _left);
            }
        })
    }
    mouseup() {
        this.render.listen(this.modalEle, "mouseup", (ev) => {
            this.isDown = false;
        })
    }
    setStyle(top, left) {
        this.render.setStyle(this.modalEle, 'top', `${top}px`);
        this.render.setStyle(this.modalEle, 'left', `${left}px`);
    }
    get modalEle() {
        return this.el.nativeElement.querySelector('.ant-modal');
    }
}
